package com.ruoyi.system.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.controller.es.EsUnService;
import com.ruoyi.system.controller.es.dto.EsSearch;
import com.ruoyi.system.domain.FyData;
import com.ruoyi.system.domain.FyPeople;
import com.ruoyi.system.domain.FyProject;
import com.ruoyi.system.domain.vo.DataTemplateVo;
import com.ruoyi.system.domain.vo.DeleteIdVo;
import com.ruoyi.system.domain.vo.ProjectTemplateVo;
import com.ruoyi.system.domain.vo.ResourcesTemplateVo;
import com.ruoyi.system.util.UniqueIdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.util.ArrayListWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.FyResources;
import com.ruoyi.system.service.IFyResourcesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 扩展资源Controller
 *
 * @author ruoyi
 * @date 2025-06-05
 */
@RestController
@RequestMapping("/system/resources")
public class FyResourcesController extends BaseController
{
    @Autowired
    private IFyResourcesService fyResourcesService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    RuoYiConfig ruoYiConfig;
    @Autowired
    private EsUnService esUnService;
    /**
     * 查询扩展资源列表
     */
//    @PreAuthorize("@ss.hasPermi('system:resources:list')")
    @GetMapping("/list")
    public TableDataInfo list(FyResources fyResources)
    {
        startPage();
        List<FyResources> list = fyResourcesService.selectFyResourcesList(fyResources);
        return getDataTable(list);
    }
    @GetMapping("/list2")
    public AjaxResult list2(FyResources fyResources)
    {
        startPage();
        List<FyResources> list = fyResourcesService.selectFyResourcesList(fyResources);
        return AjaxResult.success();
    }
    /**
     * 导出扩展资源列表
     */
//    @PreAuthorize("@ss.hasPermi('system:resources:export')")
    @Log(title = "扩展资源", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FyResources fyResources)
    {
        List<FyResources> list = fyResourcesService.selectFyResourcesList(fyResources);
        ExcelUtil<FyResources> util = new ExcelUtil<FyResources>(FyResources.class);
        util.exportExcel(response, list, "扩展资源数据");
    }

    /**
     * 获取扩展资源详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:resources:query')")
    @GetMapping( "/getInfo")
    public AjaxResult getInfo( Long reId)
    {
        return success(fyResourcesService.selectFyResourcesByReId(reId));
    }

    /**
     * 新增扩展资源
     */
//    @PreAuthorize("@ss.hasPermi('system:resources:add')")
    @Log(title = "扩展资源", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody FyResources fyResources)
    {
//        redisCache.deleteObject("home:count");
        fyResources.setReId(Long.valueOf(DateUtils.dateTimeNow()));
        EsSearch esSearch=new EsSearch();
        esSearch.setId(fyResources.getReId());
        esSearch.setLanmu("资源-扩展资源");
        esSearch.setLanmuId(3);
        esSearch.setTitle(fyResources.getFileName());
        esSearch.setContent(fyResources.getType());
        esUnService.save(esSearch);
        return toAjax(fyResourcesService.insertFyResources(fyResources));
    }

    /**
     * 修改扩展资源
     */
//    @PreAuthorize("@ss.hasPermi('system:resources:edit')")
    @Log(title = "扩展资源", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody FyResources fyResources)
    {
        EsSearch esSearch=new EsSearch();
        esSearch.setId(fyResources.getReId());
        esSearch.setLanmu("资源-扩展资源");
        esSearch.setLanmuId(3);
        esUnService.delete(esSearch);
        esSearch.setTitle(fyResources.getFileName());
        esSearch.setContent(fyResources.getType());
        esUnService.save(esSearch);
        return toAjax(fyResourcesService.updateFyResources(fyResources));
    }

    /**
     * 删除扩展资源
     */
//    @PreAuthorize("@ss.hasPermi('system:resources:remove')")
    @Log(title = "扩展资源", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteIdVo deleteIdVo)
    {
        redisCache.deleteObject("home:count");
        return toAjax(fyResourcesService.deleteFyResourcesByReIds(deleteIdVo.getReId()));
    }

    /**
     * 导出扩展资源列表
     */
//    @PreAuthorize("@ss.hasPermi('system:resources:export')")
    @Log(title = "扩展资源", businessType = BusinessType.EXPORT)
    @GetMapping("/template")
    public void template(HttpServletResponse response, FyResources fyResources) throws UnsupportedEncodingException {
        List<ResourcesTemplateVo> list = new ArrayList<>();
        ResourcesTemplateVo resourcesTemplateVo=new ResourcesTemplateVo();
        resourcesTemplateVo.setFileName("题名");
        resourcesTemplateVo.setFormat("jpg/mp3/mp4/pdf");
        resourcesTemplateVo.setCode("文件资源全名称，例：图片.jpg，人工编码填写为：图片.jpg");
        resourcesTemplateVo.setMinzu("汉");
        resourcesTemplateVo.setType("谚语");
        resourcesTemplateVo.setZhuti("事理");
        resourcesTemplateVo.setIsTop("否");
        list.add(resourcesTemplateVo);
        ExcelUtil<ResourcesTemplateVo> util = new ExcelUtil<ResourcesTemplateVo>(ResourcesTemplateVo.class);
        String fileName = URLEncoder.encode("扩展资源数据上传模版" + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        util.exportExcel(response, list, "扩展资源数据");
    }

    @PostMapping("/importData")
    @Transactional
    public AjaxResult importData(MultipartFile excelfile,MultipartFile[] files) throws Exception
    {
        ExcelUtil<ResourcesTemplateVo> util = new ExcelUtil<ResourcesTemplateVo>(ResourcesTemplateVo.class);
        List<ResourcesTemplateVo> voList = util.importExcel(excelfile.getInputStream());
        for(ResourcesTemplateVo l:voList){
            FyResources resources=new FyResources();

            String type = l.getFormat();
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type  + "/"+ DateUtils.YYYYMMDD() +"/" +  l.getCode() ;


            BeanUtils.copyBeanProp(resources,l);
            resources.setFileUrl(url);

            fyResourcesService.insertFyResources(resources);
        }
        for (MultipartFile file:files) {

            OSS ossClient = new OSSClientBuilder().build(ruoYiConfig.getEndpoint(), ruoYiConfig.getAccessKeyId(), ruoYiConfig.getAccessKeySecret());
            ObjectMetadata omd = new ObjectMetadata();
            String status = "";
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String imgName = file.getOriginalFilename();
            if (ossClient.doesBucketExist(ruoYiConfig.getBucketName())) {
                System.out.println("您已经创建Bucket：" + ruoYiConfig.getBucketName() + "。");
            } else {
                System.out.println("您的Bucket不存在，创建Bucket：" + ruoYiConfig.getBucketName() + "。");

                ossClient.createBucket(ruoYiConfig.getBucketName());
            }
            if (type == "mp4" || type.equals("mp4")) {
                omd.setContentType("video/mp4");
                status = "0";
            }
            if (type == "mp3" || type.equals("mp3")) {
                omd.setContentType("audio/mpeg");
                status = "0";
            }
            if (type == "pdf" || type.equals("pdf") || type.equals("PDF") || type == "PDF") {
                omd.setContentType("application/pdf");
                status = "0";
            }
            if (type == "jpg" || type.equals("jpg")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (type == "png" || type.equals("png")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (StringUtils.isEmpty(status)) {
                return AjaxResult.error("请输入上传正确格式的文件--> .jpg/.png/mp4/mp3/.pdf");
            }
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            ossClient.putObject(ruoYiConfig.getBucketName(), type + "/"+ DateUtils.YYYYMMDD() +"/" + imgName, file.getInputStream(), omd);
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type  + "/"+ DateUtils.YYYYMMDD() +"/" +  imgName + ruoYiConfig.getOssshuiyin();
            ossClient.setObjectAcl(ruoYiConfig.getBucketName(), type  + "/"+ DateUtils.YYYYMMDD() +"/" + imgName, CannedAccessControlList.PublicRead);
            ossClient.shutdown();
            ossClient.shutdown();
        }


        return AjaxResult.success();
    }

    @PostMapping("/importDatatest")
    @Transactional
    public AjaxResult importDatatest(MultipartFile file) throws Exception {
        ExcelUtil<ResourcesTemplateVo> util = new ExcelUtil<ResourcesTemplateVo>(ResourcesTemplateVo.class);
        List<ResourcesTemplateVo> voList = util.importExcel(file.getInputStream(),1);
        for (ResourcesTemplateVo l : voList) {
            FyResources resources = new FyResources();

            String type = l.getFormat().replaceAll("文本","pdf");
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type + "/" + DateUtils.YYYYMMDD() + "/" + l.getCode()+".pdf";
            BeanUtils.copyBeanProp(resources, l);
            resources.setFileUrl(url);
            String dateString = "2025-07-19 22:24:01";
            // 定义日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 解析字符串为 Date 对象
            Date date = sdf.parse(dateString);
            resources.setCreateTime(date);
            fyResourcesService.insertFyResources(resources);
        }
        return AjaxResult.success();
    }
}
